package com.wewins.fota.bean.dto;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.wewins.fota.bean.po.PkgVersion;
import lombok.Builder;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static org.apache.tools.ant.launch.Locator.encodeURI;

@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CheckStatusResp {
    @JsonProperty("release_start_date")
    @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone = "GMT+8")
    private Date releaseTime;

    @JsonProperty("release_note")
    private String description;

    @JsonProperty("new_firmware")
    private String version;

    @JsonProperty("download_url")
    private String url;

    @JsonProperty("file_size")
    private Integer size;

    @JsonProperty("file_size_text")
    private String sizeText;

    public CheckStatusResp fillBy(PkgVersion pkgVersion, String lang) {
        if (StringUtils.isEmpty(lang)) {
            lang = "default";
        }
        this.releaseTime = new Date(pkgVersion.getReleaseTime());
        try {
            Map<String, String> descriptionMap = JSONObject.parseObject(pkgVersion.getDescription(), Map.class);
            this.description = descriptionMap.getOrDefault(lang, "");
        } catch (Exception e) {
            this.description = pkgVersion.getDescription();
            if (this.description == null) {
                this.description = "";
            }
        }
        this.version = pkgVersion.getVersion();
        this.url = pkgVersion.getUri();
        this.size = pkgVersion.getSize();
        this.sizeText = pkgVersion.getSizeText();
        return this;
    }

    /**
     * I am a mentally retarded method. There is not logic, and dragged down the whole project.
     * but someone need me.
     *
     * @param req the param of the request to query update status.
     * @return update status
     */
    public CheckStatusResp expandDownloadUrl(CheckStatusReq req) throws IOException {
        this.url = encodeURI(this.url +
                "?product=" + req.getProduct() +
                "&imei=" + req.getImei() +
                "&old_version=" + req.getVersion() +
                "&new_version=" + this.getVersion() +
                "&auto=" + req.getAuto());
        return this;
    }
}
